﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RealSense.Light.Core
{
  /// <summary>
  /// Base class for 
  /// </summary>
  internal class ConnectionHandler : IConnection
  {
    private ISenseManager senseManager;

    public T ConnectToDevice<T>(string friendlyName, int id)
      where T : PXCMBase
    {
      if (string.IsNullOrWhiteSpace(friendlyName))
      {
        return ConnectToDevice<T>();
      }

      PXCMSession.ImplDesc description = new PXCMSession.ImplDesc();
      description.cuids[0] = id;
      description.friendlyName = friendlyName;

      T pxcmBase = null;
      RealSenseBase.StaticInvokeAndThrow(() => 
        SenseManager.SenseManager.session.CreateImpl<T>(description, out pxcmBase), 
        "creating an instance of " + friendlyName);

      return pxcmBase;
    }

    public T ConnectToDevice<T>() where T : PXCMBase
    {
      T pxcmBase = null;

      RealSenseBase.StaticInvokeAndThrow(() =>
        ServiceLocator.Instance.Get<ISenseManager>()
          .SenseManager.session.CreateImpl<T>(out pxcmBase),
          string.Format("creating an instance of {0}", typeof(T).Name));
      return pxcmBase;
    }

    private ISenseManager SenseManager
    {
      get
      {
        if (senseManager == null)
        {
          senseManager = ServiceLocator.Instance.Get<ISenseManager>();
        }
        return senseManager;
      }
    }
  }
}
